import Toast from 'tdesign-miniprogram/toast/index';
import { GoodsDetail, AddCard } from '../../../services/good/fetchGood';
import { cdnBase } from '../../../config/index';
var WxParse = require('../../../wxParse/wxParse.js');//路径为你放的路径，这里是参考
const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;
const obj2Params = (obj = {}, encode = false) => {
	const result = [];
	Object.keys(obj).forEach((key) =>
		result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
	);

	return result.join('&');
};

Page({
	data: {
		commentsList: [],
		recLeftImg,
		recRightImg,
		details: {},
		goodsTabArray: [
			{
				name: '商品',
				value: '', // 空字符串代表置顶
			},
			{
				name: '详情',
				value: 'goods-page',
			},
		],
		storeLogo: `${imgPrefix}common/store-logo.png`,
		jumpArray: [
			{
				title: '首页',
				url: '/pages/home/home',
				iconName: 'home',
			},
			{
				title: '购物车',
				url: '/pages/cart/index',
				iconName: 'cart',
				showCartNum: true,
			},
		],
		isStock: true,
		cartNum: 1,
		soldout: false,
		buttonType: 1,
		buyNum: 1,
		selectedAttrStr: '',
		skuArray: [],
		primaryImage: '',
		specImg: '',
		isSpuSelectPopupShow: false,//加购弹框
		operateType: 0,
		selectSkuSellsPrice: 0,
		maxLinePrice: 0,
		minSalePrice: 0,
		maxSalePrice: 0,
		list: [],
		goodsId: '',
		navigation: { type: 'fraction' },
		current: 0,
		autoplay: true,
		duration: 500,
		interval: 5000,
		soldNum: 0, // 已售数量
		swiperList: [],
		paramAttr: []
	},

	onLoad(query) {
		const { goodsId } = query;
		this.setData({
			goodsId: goodsId,
		});
		this.getDetail(goodsId);
	},
	getDetail(goodsId) {
		GoodsDetail({ goodsId: goodsId }).then((res) => {
			if (res.code == '0000') {
				let swiperList = [];
				if (res.data.pic) {
					swiperList.push(res.data.pic)
				}
				let reHtml = '';
				var that = this;  //这里的this是指的是当前page实例
				if (res.data.content) {
					reHtml = res.data.content
					WxParse.wxParse('article', 'html', reHtml, that, 0, 0);
				}
				let paramAttr = []
				if (res.data.param) {
					let a = res.data.param
					for (let i in a) {
						let value = a[i]
						paramAttr.push({ i, value })
					}
				}
				this.setData({
					details: res.data,
					swiperList,
					paramAttr
				});
			}
		})
	},

	//底部弹框关闭事件
	handlePopupHide() {
		this.setData({
			isSpuSelectPopupShow: false,
		});
	},
	//弹框展示状态（2.加购  1.购买）
	showSkuSelectPopup(type) {
		this.setData({
			buyType: type || 0,
			outOperateStatus: type >= 1,
			isSpuSelectPopupShow: true,
		});
	},
	//立即购买按钮 弹框展示
	buyItNow() {
		this.showSkuSelectPopup(1);
	},
	//加入购物车按钮 弹框展示
	toAddCart() {
		this.showSkuSelectPopup(2);
	},
	//购物车 首页按钮事件
	toNav(e) {
		const { url } = e.detail;
		wx.switchTab({
			url: url,
		});
	},

	showCurImg(e) {
		const { index } = e.detail;
		const { images } = this.data.details;
		wx.previewImage({
			current: images[index],
			urls: images, // 需要预览的图片http链接列表
		});
	},

	onPageScroll({ scrollTop }) {
		const goodsTab = this.selectComponent('#goodsTab');
		goodsTab && goodsTab.onScroll(scrollTop);
	},



	// 获取已选择的sku名称
	getSelectedSkuValues(skuTree, selectedSku) {
		const normalizedTree = this.normalizeSkuTree(skuTree);
		return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
			const skuValues = normalizedTree[skuKeyStr];
			const skuValueId = selectedSku[skuKeyStr];
			if (skuValueId !== '') {
				const skuValue = skuValues.filter((value) => {
					return value.specValueId === skuValueId;
				})[0];
				skuValue && selectedValues.push(skuValue);
			}
			return selectedValues;
		}, []);
	},

	normalizeSkuTree(skuTree) {
		const normalizedTree = {};
		skuTree.forEach((treeItem) => {
			normalizedTree[treeItem.specId] = treeItem.specValueList;
		});
		return normalizedTree;
	},

	selectSpecsName(selectSpecsName) {
		if (selectSpecsName) {
			this.setData({
				selectedAttrStr: selectSpecsName,
			});
		} else {
			this.setData({
				selectedAttrStr: '',
			});
		}
	},
	//加入购物车
	addCart(e) {
		const { details } = this.data;
		let params = {
			count: e.buyNum,
			goodsId: details.goodsId,
			goodsName: details.goodsName,
			sku: details.sku,
			totalAmount: details.price * e.buyNum
		}
		AddCard(params).then((res) => {
			if (res.code === "0000") {
				Toast({
					context: this,
					selector: '#t-toast',
					message: '添加成功',
					icon: 'check-circle',
					duration: 1000,
				});
				this.handlePopupHide();
			}
		})
	},
	//立即购买
	gotoBuy() {
		const { buyNum, details } = this.data;
		const goodsRequestList = [];
		goodsRequestList.push({ num: buyNum, goodsId: details.goodsId })
		wx.setStorageSync('order.goodsRequestList', JSON.stringify(goodsRequestList));
		this.handlePopupHide();
		wx.navigateTo({ url: '/pages/order/order-confirm/index' });
		// if (!isAllSelectedSku) {
		// 	Toast({
		// 		context: this,
		// 		selector: '#t-toast',
		// 		message: '请选择规格',
		// 		icon: '',
		// 		duration: 1000,
		// 	});
		// 	return;
		// }
	},
	//确定提交
	specsConfirm(e) {
		const { buyType } = this.data;
		if (buyType === 1) {
			this.gotoBuy();
		} else {
			this.addCart(e.detail);
		}
		this.setData({
			cartNum: e.detail.buyNum
		})
		// this.handlePopupHide();
	},

	changeNum(e) {
		this.setData({
			buyNum: e.detail.buyNum,
		});
	},

	onShareAppMessage() {
		// 自定义的返回信息
		const { selectedAttrStr } = this.data;
		let shareSubTitle = '';
		if (selectedAttrStr.indexOf('件') > -1) {
			const count = selectedAttrStr.indexOf('件');
			shareSubTitle = selectedAttrStr.slice(count + 1, selectedAttrStr.length);
		}
		const customInfo = {
			imageUrl: this.data.details.primaryImage,
			title: this.data.details.title + shareSubTitle,
			path: `/pages/goods/details/index?goodsId=${this.data.goodsId}`,
		};
		return customInfo;
	},

});
